<?php

session_start();
require ('config.php');
include ('includes/filtreatment_class.php');
include_once './includes/adLDAP.php'; ////for the ad auth./////


if (!isset($_REQUEST['last_message'])) {
    $_REQUEST['last_message'] = '';
}
if (isset($_REQUEST['redirection'])) {
    $filt = new Filtreatment;
    $_REQUEST['redirection'] = $filt->doTreatment($_REQUEST['redirection'], 'XSS');
}


//////////AD Authentication/////////////
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {

		$username = htmlspecialchars( $_POST['frmuser'] );
		$password = htmlspecialchars( $_POST['frmpass'] );
		
		$adldap = new adLDAP();
		
				$authUser = $adldap->authenticate($username, $password);
			if ($authUser) {

//////////Login in to DMS/////////////			
		if(isset($_POST['login']))
		{
			if(!valid_username($_POST['frmuser']))
			{
				echo "<font color=red>The username or password was invalid. Please try again.</font>";
				exit;
			}

			if(!is_dir($GLOBALS['CONFIG']['dataDir']) || !is_writeable($GLOBALS['CONFIG']['dataDir']))
			{
				echo "<font color=red>There is a problem with your dataDir. Check to make sure it exists and is writeable</font>";
				exit;
			}

			$frmuser = $_POST['frmuser'];
			$frmpass = $_POST['frmpass'];


			if ( $GLOBALS['CONFIG']['try_nis'] == "On")
			{
				$pwent = @split(":",`ypmatch $frmuser passwd`);
				if(isset($pwent))
					$cryptpw = @crypt(stripslashes($frmpass),substr($pwent[1],0,2));
			}

			$query = "SELECT id, username, password FROM {$GLOBALS['CONFIG']['db_prefix']}user WHERE username = '$frmuser' AND password = password('$frmpass')";
			$result = mysql_query("$query") or die ("Error in query: $query. " . mysql_error());

			if ( $GLOBALS['CONFIG']['try_nis'] == "On")
			{
				if (mysql_num_rows($result) == 0)
				{
				  if (isset($pwent) && isset($cryptpw) && strcmp($cryptpw,$pwent[1]) == 0)
				  {
					$query = "SELECT id, username, password FROM {$GLOBALS['CONFIG']['db_prefix']}user WHERE username = '$frmuser'";
					$result = mysql_query("$query") or die ("Error in query: $query. " . mysql_error());
				  }
				}
			}

			if (mysql_num_rows($result) == 1)
			{
				// register the user's ID
				list($id, $username, $password) = mysql_fetch_row($result);
				// initiate a session
				$_SESSION['uid'] = $id;
				// redirect to main page
				if(isset($_REQUEST['redirection']))
					header('Location:' . $_REQUEST['redirection']);
				else
					header('Location:out.php');
				mysql_free_result ($result);	
				// close connection
			}
			else
				// login/pass check failed
			{
				mysql_free_result ($result);
				// redirect to error page
				header('Location: error.php?ec=0');
			}

		}
		elseif($GLOBALS['CONFIG']['authen'] =='kerbauth')
		{

				// check login and password
				// connect and execute query
				if (!isset($_COOKIE['AuthUser']))
				{
						header('Location: https://secureweb.ucdavis.edu:443/cgi-auth/sendback?'.$GLOBALS['CONFIG']['base_url']);
				}
				else
				{
						list ($userid, $id2, $id3) = split ('[-]', $_COOKIE['AuthUser']);
						//// query to get id num from username
						$query = "SELECT id FROM {$GLOBALS['CONFIG']['db_prefix']}user WHERE username='$userid'";
						$result = mysql_query($query) or die ('Error in query: '.$query . mysql_error());
						// if row exists then the user has an account
						if (mysql_num_rows($result) == 1)
						{
								// initiate a session
								session_start();
								// register the user's ID
								session_register('uid');
								list($id) = mysql_fetch_row($result);
								$_SESSION['uid'] = $id;
								// redirect to main page
								header('Location:out.php');
								mysql_free_result ($result);	
								// close connection
						}
						// User passed auth, but does not have an account
						else 
						{
								header('Location:error.php?ec=19');
						}
				}
		}	

			  
			  
			  

	}
	
	else
		// AD auth  failed
	{
		mysql_free_result ($result);
		// redirect to error page
		header('Location: error.php?ec=0');
	}
}

elseif(!isset($_POST['login']) && $GLOBALS['CONFIG']['authen'] =='mysql')
{
    if(is_dir('install'))
    {
        $install_msg = 'hoi';
    }
    else
    {
        $install_msg = '';
    }    

	
    ?>
        <html>
			<head>
				<link rel="stylesheet" type="text/css" href="/css/login.css" />
				<title><?php echo $GLOBALS['CONFIG']['title']; ?></title>
			</head>
			<body>
					<div id="container">
						<div id="content">
							<div id="loginform">
									<form action="index.php" method="post">
									<?php
										if(isset($_REQUEST['redirection']))
											echo '<input type="hidden" name="redirection" value="' . $_REQUEST['redirection'] . '">' . "\n"; 
									?>										
										<div class="text">
											Username
										</div>	
										<div class="inputfields">
											<input type="Text" name="frmuser" size="15">
										</div>
										
										<div class="text">
											Password
										</div>
										<div class="inputfields">
											<input type="password" name="frmpass" size="15">
										</div>	
										
										<div id="loginbutton">
											<input type="Submit" name="login" value="Login">
										</div>
									</form>
							</div>
						</div>	
					</div>
			</body>
		</html>


<?php
        draw_footer();
}
else
{
        echo 'Check your config';
}
?>
